import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:xiaomi/app/models/hotSellModel.dart';
import 'package:xiaomi/app/modules/tools/httpClient.dart';
import 'package:xiaomi/main.dart';

class GoodListController extends GetxController {
  //TODO: Implement GoodListController
  ScrollController scrollController = ScrollController();
  RxList<HotSellItemModel> goodlistData = <HotSellItemModel>[].obs;
  int currentPage = 1;
  int pageSize = 8;
  RxBool isLoaddingMore = false.obs;
  RxBool isEndding = false.obs;
  RxInt selectIndex = 1.obs;
  RxInt sameItem = (-1).obs;
  var sortList = [
    {'id': 1, "title": '综合', 'field': 'all', 'sore': -1},
    {'id': 2, "title": '销量', 'field': 'salecount', 'sore': -1},
    {'id': 3, "title": '价格', 'field': 'price', 'sore': -1},
    {'id': 4, "title": '筛选', 'sore': -1},
  ];
  @override
  void onInit() {
    super.onInit();
    _getGoodlistData(sid: Get.arguments['sid']);
    scrollController.addListener(() {
      if (scrollController.position.pixels >=
          scrollController.position.maxScrollExtent) {
        _getGoodlistData(sid: Get.arguments['sid']);
      }
    });
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void tapindex(Map<String, dynamic> map) {
    if ((selectIndex.value == 2 || selectIndex.value == 3) &&
        selectIndex.value == map['id']) {
      sameItem.value = sameItem.value * -1;
    } else {
      selectIndex.value = map['id'];
    }

    print('${selectIndex.value}');
    update();
  }

  void _getGoodlistData({String? sid, String? keyword}) async {
    if (isEndding.value == true || isLoaddingMore.value == true) {
      return;
    }
    isLoaddingMore.value = true;
    String path = sid == null
        ? 'api/plist?keywords=$keyword&page=$currentPage&pageSize=$pageSize'
        : 'api/plist?cid=$sid&page=$currentPage&pageSize=$pageSize';
    print('列表界面请求地址  ： $path');

    var rsp = await HttpClient.get(path);

    if (rsp != null && isEndding.value == false) {
      goodlistData.addAll(HotSellModel.fromJson(rsp.data).result!);
      currentPage++;
      isLoaddingMore.value = false;

      isEndding.value =
          HotSellModel.fromJson(rsp.data).result!.length < 8 ? true : false;

      update();
    }
  }
}
